package com.heima.lock.sjms.单例模式.单例问题04;

/**
 * @author 陈辉
 * @data 2024 11:07
 *
 * 设计模式：编程套路，从编程发展至今，一共总结出32套优秀的编程套路。
 *
 * 单例：一个类在全局只产生一个对象
 * 单例是可以通过反射/反序列化操作破坏的!
 */

public class Student { }

class Demo{

    public static Student stu;

    public static void main(String[] args) {
        //t1
        new Thread(()->{
            Student stu1 = getStu();
            System.out.println("stu1 = " + stu1);
        }).start();

        //t2
        new Thread(()->{
            Student stu2 = getStu();
            System.out.println("stu2 = " + stu2);
        }).start();
    }

    public static Student getStu(){
        synchronized ("abc") {
            if (stu == null){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                stu = new Student();
            }
        }

        return stu;
    }
}
